"""
deepseek多轮问答
pip install --upgrade 'openai>=1.0'
保证 Python 版本至少为 3.7.1，Node.js 版本至少为 18，OpenAI SDK 版本不低于 1.0.0。
编程环境：python3.10.16,conda robotWX)
"""
from openai import OpenAI

class DeepseekAI:
    def __init__(self):
        self.api_key = "" # 请填写你的apikey
        self.base_url = "https://api.deepseek.com"
        self.model = "deepseek-chat"
        self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
        self.messages = []

    def answer(self,user_input):
        message = {"role": "user", "content": user_input}
        self.messages.append(message)
        length = len(self.messages)
        # 限制多轮问答的信息条数，保留近2轮问答信息即可，否则token数会增加太多
        if length > 4:
            self.messages = self.messages[2:]  # 从索引2开始切片，直到列表末尾

        #print('len= ' + str(length))
        #print(self.messages)
        response = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=self.messages
        )

        self.messages.append(response.choices[0].message)
        answer = response.choices[0].message.content
        #print(messages)
        #print(f"Messages Round 1: {messages}")
        return answer



if __name__ == "__main__":
    sp = DeepseekAI()
    while True:
        question = input('请输入你要问的问题？')
        """
        mes,an = sp.answer(question)
        print('mes：', mes)
        print('AI的回复是：',an )
        """
        an = sp.answer(question)
        print('AI的回复是：', an)

